
require "Common/define"
require "Logic/CtrlManager"
require "Logic/Config"
--require "Logic/ItemType"
require "Net/send_Msg"
require "proto/item/message/ReqUseItemMessage"
require "proto/item/message/ReqResolveItemMessage"


itemHandler = itemHandler or {};
G.serverData = G.serverData or {};
  
local sub_type = Config.sub_type_itemInfo

function itemHandler.receiveItemUpdate(msg)
	if msg.state == 0 then
		local item
		local mi = msg.item
		if msg.bagType == EnumConst.ItemTableEnum.Equip then
			item = ClientEquipData.New(mi.itemId,mi.itemModelId,mi.num,true)
		--else
			--item = ClientItemData.New(mi.itemId,mi.itemModelId,mi.num,true)
		end
		--[[item["itemId"] = tostring(msg.item.itemId);
		item["itemModelId"] = msg.item.itemModelId;
		item["num"] = msg.item.num;
		item["tabType"] = msg.bagType;]]

		if msg.bagType == EnumConst.ItemTableEnum.Equip then
			logicMgr.EquipManager.setItemData(tostring(msg.item.itemId),tostring(msg.item.num),msg.sourceCode,msg.params);
		elseif msg.bagType == EnumConst.ItemTableEnum.Rune then
			--local runeInfo = logicMgr.RuneManager.FormationRuneInfo(msg.item)
			logicMgr.RuneManager.UpDataStuffRuneData(tostring(msg.item.itemId),tostring(msg.item.num))
		else
			logicMgr.ItemManager.setItemData(tostring(msg.item.itemId),tonumber(tostring(msg.item.num)),msg.sourceCode,msg.params);
			if tonumber(msg.item.itemModelId) == CurrencyEnum.PetCoin then
				FireEvent(Config.EventType.PETSHOP_RefreshPetCoinNum)
			end
		end
		FireEvent(Config.EventType.Fresh_Bag);
	end
end

function itemHandler.receiveItemAdd(msg)
	--log("itemHandler.receiveItemAdd");
	--dataTable.PrintTable(msg);
	if msg.state == 0 then
		if msg.bagType == EnumConst.ItemTableEnum.Fragment then
			StrangeFragmentManager.ResAddFragment(msg.item,msg.sourceCode,msg.params)
			StrangeFragmentManager.UpdateFragmentList()
		elseif msg.bagType == EnumConst.ItemTableEnum.Rune then
			local runeInfo = logicMgr.RuneManager.FormationRuneInfo(msg.item)
			logicMgr.RuneManager.AddStuffRune(runeInfo)
		else
			--local item
			--local mi = msg.item
			--if msg.bagType == EnumConst.ItemTableEnum.Equip then
				--item = ClientEquipData.New(mi.itemId,mi.itemModelId,mi.num,true)
				--if mi.parameters ~= nil then
				--	local refine = decodeJsonStrToTabel(msg.item.parameters);
				--	item:SetRefine(tonumber(refine["STRENGTH_LEVEL"]),tonumber(refine["STRENGTH_EXP"]))
				--end
				--todo 装备的？
				--item.attributes = mi.attributes;
			--else
			--	item = ClientItemData.New(mi.itemId,mi.itemModelId,mi.num,true)
			--end

			--[[item["itemId"] = tostring(msg.item.itemId);
			item["itemModelId"] = msg.item.itemModelId;
			item["num"] = msg.item.num;
			item["tabType"] = msg.bagType;
			item["attributes"] = msg.item.attributes;
			if msg.item.parameters ~= nil then
				local refine = decodeJsonStrToTabel(msg.item.parameters);
				item["curRfLevel"] = tonumber(refine["STRENGTH_LEVEL"]);
				item["exp"] = tonumber(refine["STRENGTH_EXP"]);
			end]]
			local Enum = EnumConst.ItemTableEnum
			if msg.bagType == Enum.Equip then
				logicMgr.EquipManager.addItemData(msg.item,msg.sourceCode,msg.params);
			elseif msg.bagType == Enum.Item or
					msg.bagType == Enum.Hero or
					msg.bagType == Enum.Frame then
				logicMgr.ItemManager.addItemData( msg.item,msg.sourceCode,msg.params,msg.bagType);
			end
			if(msg.bagType==Enum.Frame)then
				RedDotsHeadFrameHandler.showRed=true
				FireEvent(Config.EventType.HeadFrame);
			end
		end
		
		FireEvent(Config.EventType.Fresh_Bag);
	end
end

function itemHandler.receiveItemRemove(msg)
	--log("itemHandler.receiveItemRemove");
	--dataTable.PrintTable(msg);
	if msg.state == 0 then
		if msg.bagType == EnumConst.ItemTableEnum.Equip then
			logicMgr.EquipManager.delItemData(msg.itemId,msg.sourceCode,msg.params);
		elseif msg.bagType == EnumConst.ItemTableEnum.Item then
			logicMgr.ItemManager.delItemData(msg.itemId,msg.sourceCode,msg.params);
		elseif msg.bagType == EnumConst.ItemTableEnum.Hero then
			logicMgr.ItemManager.delItemData(msg.itemId,msg.sourceCode,msg.params);
		elseif msg.bagType == EnumConst.ItemTableEnum.Fragment then
			--logicMgr.ItemManager.delItemData(msg.itemId);
		elseif msg.bagType == EnumConst.ItemTableEnum.Rune then
			logicMgr.RuneManager.DeleteStuffRuneData(msg.itemId);
		end
		FireEvent(Config.EventType.Fresh_Bag);
	end
end

function itemHandler.receiveItemsRemove(msg)
	--log("itemHandler.receiveItemsRemove");
	--dataTable.PrintTable(msg);
	if msg.state == 0 then
		if msg.bagType == EnumConst.ItemTableEnum.Equip then
			for i = 1, #msg.itemId do
				logicMgr.EquipManager.delItemData(msg.itemId[i],msg.sourceCode,msg.params);
			end
		elseif msg.bagType == EnumConst.ItemTableEnum.Item then
			for i = 1, #msg.itemId do
				logicMgr.ItemManager.delItemData(msg.itemId[i],msg.sourceCode,msg.params);
			end
		elseif msg.bagType == EnumConst.ItemTableEnum.Hero then
			for i = 1, #msg.itemId do
				logicMgr.ItemManager.delItemData(msg.itemId[i],msg.sourceCode,msg.params);
			end
		elseif msg.bagType == EnumConst.ItemTableEnum.Fragment then
			-- for i = 1, #msg.itemId do
			-- 	logicMgr.ItemManager.delItemData(msg.itemId[i]);
			-- end
		end
		FireEvent(Config.EventType.Fresh_Bag);
	end
end

function itemHandler.receiveItemInfos(msg)
	--log("itemHandler.receiveItemInfos");
	--dataTable.PrintTable(msg);
	if msg.state == 0 then
		if msg.bagType == EnumConst.ItemTableEnum.Fragment then
			if #msg.items > 0 then
				for key, item in pairs(msg.items) do
					StrangeFragmentManager.ResAddFragment(item,-1,"")
				end
				StrangeFragmentManager.UpdateFragmentList()
			end
		else
			for i = 1, #msg.items do
				--local item
				--local mi = msg.items[i]
				--if msg.bagType == EnumConst.ItemTableEnum.Equip then
				--	item = ClientEquipData.New(mi.itemId,mi.itemModelId,mi.num,true)
				--	if mi.parameters ~= nil then
				--		local refine = decodeJsonStrToTabel(msg.item.parameters);
			--			item:SetRefine(tonumber(refine["STRENGTH_LEVEL"]),tonumber(refine["STRENGTH_EXP"]))
			--		end
				--else
					--item = ClientItemData.New(mi.itemId,mi.itemModelId,mi.num,true)
			--	end
				--[[item["itemId"] = tostring(msg.items[i].itemId);
				item["itemModelId"] = msg.items[i].itemModelId;
				item["num"] = msg.items[i].num;
				item["tabType"] = msg.bagType;]]
				local Enum = EnumConst.ItemTableEnum
				if msg.bagType == Enum.Equip then
					logicMgr.EquipManager.addItemData(msg.items[i],-1,"");
				elseif msg.bagType == Enum.Rune then
					local runeInfo = logicMgr.RuneManager.FormationRuneInfo(msg.items[i])
					logicMgr.RuneManager.AddStuffRune(runeInfo)
				elseif msg.bagType == Enum.Item or
						msg.bagType == Enum.Hero or
						msg.bagType == Enum.Frame then
					logicMgr.ItemManager.addItemData(msg.items[i],-1,"",msg.bagType);
				end
			end
		end
		FireEvent(Config.EventType.Fresh_Bag)
	end
end

function itemHandler.useItemBack(msg)
	--logError("itemHandler.useItemBack");
	--dataTable.PrintTable(msg);
	if msg.state == 0 then
		local itemData = {};
		itemData["itemId"] = tostring(msg.itemId);
		itemData["itemModelId"] = msg.itemModelId;
		itemData["itemNum"] = msg.itemNum;
		itemData["rewardItems"] = msg.rewardItems;
		itemData["parameters"] = msg.parameters;
		logicMgr.ItemManager.resUseItemBack(itemData);

		AudioManager.TryPlaySoundItemChange(tostring(msg.itemModelId),false)
	end
end

function itemHandler.sendReqUseItem(itemData)
	local req = ReqUseItemMessage.New();
	req["itemId"] = itemData.itemId;
	req["itemModelId"] = itemData.itemModelId;
	req["itemNum"] = itemData.itemNum;
	req["parameters"] = itemData.parameters;
	sendReqMessage(req);
end


--物品属性变更
--[[function itemHandler.updatePackge(msg)
	local itemInfo = {}
	itemInfo = G.serverData["itemInfo"]
	--local data = itemInfo["itemList"];
    if itemInfo == nil then
        return;
    end
	for k,v in pairs(itemInfo) do
		if msg.bagType == v["bagType"] then
			for k1, v1 in pairs(v["items"]) do
				if v1["itemId"] == tostring(msg.item.itemId) then
					v1["num"] =  msg.item.num;
					break;
				end
			end
		end
	end

	FireEvent(Config.EventType.Fresh_Bag,nil);
	FireEvent(Config.RedPoint.RP_Bag);
end]]

function itemHandler.receiveResolveItem(msg) --- 道具分解返回
	--log("itemHandler.receiveResolveItem");
	--dataTable.PrintTable(msg);
	if msg.state ==0 then
		FireEvent(Config.EventType.ItemResolve);
	end
end

function itemHandler.sendResolveItem(tableItem) -- 道具分解发送
	local req = ReqResolveItemMessage.New();
    local items  ={};
    for i = 1, #tableItem do
        local item = ItemInfo.New();
        item.itemId = tableItem[i].itemId;
        item.itemModelId = tableItem[i].itemModelId;
        item.quality = tableItem[i].quality;
        item.num = tableItem[i].num;
        item.isbind = 0;
        item.gridId = tableItem[i].gridId;
        item.lostTime = 0;
        item.attributes = {};
        item.parameters = "";
        table.insert(items,item);
    end
    req.items =items;
    sendReqMessage(req);
end

function itemHandler.getItemInfoByItemId(bagtype,itemId)

    local bagitem = G.serverData["itemInfo"][bagtype];
    if bagitem ~= nil then
        for i=1,#bagitem.items do
            if(bagitem.items[i].itemId == itemId) then
                return bagitem.items[i];
            end
        end
    end

end

--返回当前物品所占背包的格子数量
function itemHandler.GetRemainBagBoxNum(type)

	local num = 0;
	local typeBagData = G.serverData["itemInfo"][type];
	if typeBagData == nil then
		return 0;
	else
		num = #typeBagData ;
	end
	return num;
end

function itemHandler.hasBetterSkill()

    local hasEquipSkill = G.serverData["equipSkill"];
    if hasEquipSkill == nil then
        return false;
    end

    local skillbag = G.serverData["roleSkill"];

    if skillbag == nil or #skillbag <= 0 then
        return false;
    end

    for i=1,#hasEquipSkill do
        local itemid = hasEquipSkill[i];
        if itemid == 0 and itemHandler.hasUnEquipedSkill() then
            return true;
        end
    end

    return false;
end


function itemHandler.hasUnEquipedSkill()

    local skillbag = G.serverData["roleSkill"];

    if skillbag == nil or #skillbag <= 0 then
        return false;
    end

    for i=1,#skillbag do
        if not itemHandler.hasEquiped(skillbag[i])  then
            return true
        end
    end

    return false;
end

function itemHandler.hasEquiped(skillid)

    local equipskill = G.serverData["equipSkill"];

    return indexofTable(equipskill,skillid) > 0;

end

function itemHandler.hasEquipedSameSkill(modelid)


    local equipskill =  G.serverData["equipSkill"];
    local comSkillbean = G.dataTable["T_skillbase"][tostring(modelid)];
    for i=1,4 do
        local equipitem ;

        equipitem = itemHandler.getItemInfoByItemId(5,equipskill[i]);

        if equipitem ~= nil  then

            local skillbean = G.dataTable["T_skillbase"][tostring(equipitem.itemModelId)];
            if skillbean.f_SkillType == comSkillbean.f_SkillType and  skillbean.f_SkillQuality >=  comSkillbean.f_SkillQuality then
                return true;
            end
        end
    end

    return false;
end